﻿using AspNetCoreRateLimit;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Linq;
using System.Threading.Tasks;

namespace RuoVea.ExWeb.IPLimit
{
    /// <summary>
    /// 通常在项目中，Authorization授权是少不了了，加入限流后，在被限流的接口调用后，
    /// 限流拦截器使得跨域策略失效，故重写拦截器中间件，继承IpRateLimitMiddleware 
    /// 即可：
    /// </summary>
    public class IPLimitMiddleware : IpRateLimitMiddleware
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="next"></param>
        /// <param name="processingStrategy"></param>
        /// <param name="options"></param>
        /// <param name="counterStore"></param>
        /// <param name="policyStore"></param>
        /// <param name="config"></param>
        /// <param name="logger"></param>
        public IPLimitMiddleware(RequestDelegate next, IProcessingStrategy processingStrategy, IOptions<IpRateLimitOptions> options, IRateLimitCounterStore counterStore, IIpPolicyStore policyStore, IRateLimitConfiguration config, ILogger<IpRateLimitMiddleware> logger)
            : base(next, processingStrategy, options, counterStore, policyStore, config, logger)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="rule"></param>
        /// <param name="retryAfter"></param>
        /// <returns></returns>
        public override Task ReturnQuotaExceededResponse(HttpContext httpContext, RateLimitRule rule, string retryAfter)
        {
            httpContext.Response.Headers.Append("Access-Control-Allow-Origin", "*");
            return base.ReturnQuotaExceededResponse(httpContext, rule, retryAfter);
        }
    }
}
